package com.lely.springcloud.controller;

import com.lely.springcloud.lb.LoadBalancer;
import java.net.URI;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author lely
 * @create 2020-02-18 17:23
 **/
@RestController
@Slf4j
public class OrderController {
    //public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://MYPROVIDE-SERVICE";
    @Resource
    private RestTemplate restTemplate;

    /**
     * 自定义负载均衡规则
     */
    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;            //用来测试，查看集群微服务的实例，无实际用处

    /**
     * http://localhost/consumer/payment/create?serial=javaSjms002
     */
    // @GetMapping("/consumer/payment1/create")
    // public CommonResult<Payment> create(@RequestBody Payment payment) {
    //     return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    // }
    //
    // /**
    //  * http://localhost/consumer/payment/get/31
    //  */
    // @GetMapping("/consumer/payment1/get/{id}")
    // public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
    //     return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    // }
    //
    // /**
    //  * http://localhost/consumer/payment/getForEntity/31
    //  */
    // @GetMapping("/consumer/payment1/getForEntity/{id}")
    // public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {
    //     ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    //     if (entity.getStatusCode().is2xxSuccessful()) {
    //         return entity.getBody();
    //     }
    //     return new CommonResult<>(444, "操作失败");
    // }

    // http://localhost/consumer/payment/payment/lb   路由规则: 轮询
    @GetMapping(value = "/consumer/payment1/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("MYPROVIDE-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

    /**    http://localhost/consumer/payment1/zipkin   链路跟踪 zipkin+sleuth   */
    // @GetMapping("/consumer/payment/zipkin")
    // public String paymentZipkin() {
    //     return restTemplate.getForObject("http://localhost:8081/payment/zipkin/", String.class);
    // }

}
